<div class="layuimini-container layuimini-page-anim" divname="admin">
    <div class="layuimini-main">

        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" action="">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">设备SN</label>
                            <div class="layui-input-inline">
                                <input type="text" maxlength="16" name="DeviceID" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">设备名称</label>
                            <div class="layui-input-inline">
                                <input type="text" maxlength="30" name="DeviceName" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary" lay-submit lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索</button>
                            <!-- <button id="btntest" type="submit" class="layui-btn layui-btn-primary" lay-filter="data-test-btn">
                                <i class="layui-icon"></i> 测试
                            </button>
                            -->
                        </div>
                    </div>
                </form>
            </div>

        </fieldset>

        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="showDefault"> 出厂默认值 </button>
                <button class="layui-btn layui-btn-sm layui-btn-danger data-delete-btn" lay-event="delete"> 删除 </button>
            </div>
        </script>

        <table class="layui-hide" id="DevicePageTable" lay-filter="DevicePageTableFilter"></table>

        <script type="text/html" id="currentTableBar">
            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="edit">编辑</a>
            <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">删除</a>
        </script>

    </div>
</div>
<style>
    .label_online {
        color: #7FFF00;
    }

    .label_offline {
        color: #DC143C;
    }
</style>
<script>

    layui.use(['form', 'table', 'miniPage', 'element', 'faceAPI'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table,
            miniPage = layui.miniPage;
        var faceAPI = layui.faceAPI;
        var tabDatas = null;
        //$('#btntest').on('click', function () {
        //    var that = this;
        //    layer.tips('只想提示地精准些', that); //在元素的事件回调体中，follow直接赋予this即可
        //});

        table.render({
            elem: '#DevicePageTable',
            //**************************异步请求开始***********************
            url: 'api/FaceDevice/GetDeviceTable',
            method: 'post',
            headers: {
                //token: 'sasasas',
                Authorization: "Bearer " + faceAPI.GetJWTToken()
            },//增加Token验证头
            request: {
                pageName: 'pageIndex', //页码的参数名称，默认：page
                limitName: 'pageSize' //每页数据量的参数名，默认：limit
            },
            parseData: function (res) { //res 即为原始返回的数据
                if (res.errCode == 0) {
                    var data = res.content;
                    var ret = {
                        "code": res.errCode, //解析接口状态
                        "msg": res.error, //解析提示文本
                        "count": data.totalCount, //解析数据长度
                        "data": data.dataList //解析数据列表
                    };
                    return ret;

                } else {
                    /*layer.open({
                        title: '请求错误',
                        content: '(' + res.errCode + ')' + res.error
                    });  */

                    return {
                        "code": 0, //解析接口状态
                        "msg": '', //解析提示文本
                        "count": 0, //解析数据长度
                        "data": [] //解析数据列表
                    };
                }

            },
            //**************************异步请求结束***********************

            toolbar: '#toolbarDemo',
            defaultToolbar: ['filter', 'exports', 'print', {
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips'
            }],
            cols: [[
                { type: "checkbox", width: 50 },
                { field: 'id', width: 80, title: 'ID', sort: true },
                { field: 'deviceID', width: 170, title: 'SN', sort: true },
                { field: 'deviceName', width: 200, title: '名称', sort: true },
                { field: 'parameterFirmwareMsg', width: 90, title: '版本号' },
                {//出入类型 0,入门；1，出门
                    field: 'parameterAccessType', width: 90, title: '出入类型',
                    templet: function (d) {
                        if (d.parameterAccessType == 0) return '入门';
                        return "出门";
                    }
                },
                {
                    field: 'parameterKeepOpenDoor', width: 90, title: '开门保持',
                    templet: function (d) {
                        return d.parameterKeepOpenDoor + "秒";
                    }
                },
                {//免验证开门 1--启用；0--禁用
                    field: 'parameterLaissezSwitch', width: 90, title: '免验证',
                    templet: function (d) {
                        if (d.parameterLaissezSwitch == 1) return '启用';
                        return "禁用";
                    }
                },
                {//最近保活时间
                    field: 'lastKeepaliveTime', width: 90,  title: '状态', sort: true,
                    templet: function (d) {
                        var lastTime = dayjs(d.lastKeepaliveTime, "YYYY-MM-DD HH:mm:ss");
                        var onlineTime = dayjs(d.onlineTime, "YYYY-MM-DD HH:mm:ss");
                        var second = dayjs().diff(onlineTime, 'second');
                        //console.log("渲染字段 LAY_TABLE_INDEX = " + d.LAY_TABLE_INDEX);
                        //console.log(d);
                        var stip;
                        stip = '<span LAY_TABLE_INDEX="' + d.LAY_TABLE_INDEX + '" name="Onlinestatus" class="label ';
                        if (second < 300)
                            stip = stip + '  label_online">在线</span>';
                        else
                            stip = stip + '  label_offline">离线</span>';

                        return stip;
                    }
                },
                { title: '操作', minWidth: 120, toolbar: '#currentTableBar', align: "center" }
            ]],
            limits: [10, 15, 20, 25, 50, 100],
            limit: 15,
            page: true,
            skin: 'line',
            done: function (res, curr, count) {
                //如果是异步请求数据方式，res即为你接口返回的信息。
                //如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度

                if (res.count > 0) {
                    var iTipIndex = 0;
                    tabDatas = res.data;
                    $("[lay-id=DevicePageTable] [name=Onlinestatus]").mouseenter(Onlinestatus_mouseenter);


                }
            }
        });

        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            var result = data.field;
            //执行搜索重载
            table.reload('DevicePageTable', {
                page: {
                    curr: 1
                }
                , where: result
            }, 'data');

            return false;
        });


        /*
        //监听测试
        $('#btntest').on('click', function () {

            var openWH = miniPage.getOpenWidthHeight();
            var content = miniPage.getHrefContent('page/Device/test.html');//加载默认参数页面

            var index = layer.open({
                title: 'test',
                type: 1,
                shade: 0.2,
                maxmin: true,
                shadeClose: true,
                area: [openWH[0] + 'px', openWH[1] + 'px'],
                offset: [openWH[2] + 'px', openWH[3] + 'px'],
                content: content
            });
            return false;
        });*/

        /**
         * toolbar事件监听
         */
        table.on('toolbar(DevicePageTableFilter)', function (obj) {
            if (obj.event === 'showDefault') {   // 监听添加操作

                var openWH = miniPage.getOpenWidthHeight();
                faceAPI.DevicePageDefault = null;

                faceAPI.Ajax({
                    type: 'Get',
                    data: { DeviceIDs },
                    url: '/api/FaceDevice/GetDefaultValue',
                    success: function (result) {
                        if (result.result == false) {
                            layer.alert(result.error, { icon: 2 });
                        }
                        else {
                            //显示弹层
                            faceAPI.DevicePageDefault = result.content;
                            var content = miniPage.getHrefContent('page/Device/default.html');//加载默认参数页面

                            var index = layer.open({
                                title: '设备出厂参数默认值',
                                type: 1,
                                shade: 0.2,
                                maxmin: true,
                                shadeClose: true,
                                area: [openWH[0] + 'px', openWH[1] + 'px'],
                                offset: [openWH[2] + 'px', openWH[3] + 'px'],
                                content: content
                            });
                            $(window).on("resize", function () {
                                layer.full(index);
                            });
                        }

                    }
                });

            }
            else if (obj.event === 'delete') {  // 监听删除操作
                var checkStatus = table.checkStatus('DevicePageTable')
                    , data = checkStatus.data;
                var DeviceIDs = [];
                //console.log(data);
                data.forEach(function (item, index) { DeviceIDs.push(item.id); });
                if (DeviceIDs.length == 0) {
                    id
                    layer.alert('请勾选需要删除的设备');
                    return;
                }
                faceAPI.Ajax({
                    type: 'Post',
                    data: { DeviceIDs },
                    url: '/api/FaceDevice/Delete',
                    success: function (result) {
                        if (result.result == false) {
                            layer.alert(result.error, { icon: 2 });
                        }
                        else {
                            //刷新页面
                            table.reload('DevicePageTable', {
                                page: {
                                    curr: 1
                                }
                            }, 'data');
                        }

                    }
                });
            }
        });

        table.on('sort(DevicePageTableFilter)', function (obj) {
            if (tabDatas != null) {

                $("[lay-id=DevicePageTable] [name=Onlinestatus]").mouseenter(Onlinestatus_mouseenter);
            }
        });

        // 在线离线状态显示提示框
        var iMouseenter_TipIndex = 0;
        function Onlinestatus_mouseenter() {
            var that = this;
            if (iMouseenter_TipIndex > 0)
                layer.close(iMouseenter_TipIndex);
            var spn = $(that);
            var iItemIndex = spn.attr("LAY_TABLE_INDEX");
            var row = tabDatas[iItemIndex];
            var sHtml = '';

            var lastTime = dayjs(row.lastKeepaliveTime, "YYYY-MM-DD HH:mm:ss");
            var onlineTime = dayjs(row.onlineTime, "YYYY-MM-DD HH:mm:ss");
            var second = dayjs().diff(onlineTime, 'second');


            sHtml = '<ul><li><span>SN:' + row.deviceID + '</span></li><br/>';
            sHtml = sHtml + '<li><span>最近连线时间：' + row.onlineTime + '</span> </li>';
            sHtml = sHtml + '<li><span>距离现在时间：' + second + '秒</span></li><br/> ';

            second = dayjs().diff(lastTime, 'second');
            sHtml = sHtml + '<li><span>最近保活时间：' + row.lastKeepaliveTime + '</span></li>';
            sHtml = sHtml + '<li><span>距离现在时间：' + second + '秒</span></li> ';
            sHtml = sHtml + '</ul>'

            iMouseenter_TipIndex = layer.tips(sHtml, that, { area: ['230px', '160px'] });
        }

        table.on('tool(DevicePageTableFilter)', function (obj) {
            var data = obj.data;

            if (obj.event === 'edit') {

                var content = miniPage.getHrefContent('page/Device/update.html');
                var openWH = miniPage.getOpenWidthHeight();
                faceAPI.DevicePageUpdate = null;//向layer页面传值，传值主要代码
                faceAPI.DevicePageUpdateResult = null;
                faceAPI.Ajax({
                    type: 'Get',
                    url: '/api/FaceDevice/GetDeviceDetail?ID=' + data.id,
                    success: function (result) {
                        if (result.result == false) {
                            layer.alert(result.error, { icon: 2 });
                        }
                        else {
                            //显示弹层
                            faceAPI.DevicePageUpdate = result.content;
                            var index = layer.open({
                                title: '编辑设备参数',
                                type: 1,
                                shade: 0.2,
                                maxmin: true,
                                shadeClose: true,
                                area: [openWH[0] + 'px', openWH[1] + 'px'],
                                offset: [openWH[2] + 'px', openWH[3] + 'px'],
                                content: content,
                                end: function (layero, index) {

                                    var rst = faceAPI.DevicePageUpdateResult;
                                    //console.log(rst);
                                    if (rst != null && rst.result) {
                                        /*var newuser = rst.content;
                                        //执行搜索重载
                                        obj.update({
                                            phone: newuser.phone,
                                            role: newuser.Role
                                        });*/
                                    };

                                }
                            });
                            $(window).on("resize", function () {
                                layer.full(index);
                            });
                        }

                    }
                });
                return false;
            }
            else if (obj.event === 'delete') {


                layer.confirm('操作确认：删除设备[' + data.deviceID + '(' + data.deviceName + ')]?', function (index) {
                    var DeviceIDs = [];
                    DeviceIDs.push(data.id);
                    faceAPI.Ajax({
                        type: 'Post',
                        data: { DeviceIDs },
                        url: '/api/FaceDevice/Delete',
                        success: function (result) {
                            if (result.result == false) {
                                layer.alert(result.error, { icon: 2 });
                            }
                            else {
                                //刷新页面
                                obj.del();
                            }

                        }
                    });


                    layer.close(index);
                });
            }
        });
    });



</script>